var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken')
const secretKey = 'k';



 
//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');
 
// 产生6位随机数(用来生成短信验证码的)
function getCode() {
	let str = "";
	for (let i = 0; i < 6; i++) {
		str += parseInt(Math.random() * 10)
	}
	return str;
}
 
/** 
 *这里写post请求接口，前端调用 http://localhost:3000/api/get_sms
 *默认端口是3000，也可以在./bin/www里面修改
 */
router.post('/get_sms', function(req, res, next) {
	let phoneNum = req.body.phone;  //获取前端参数phone
	console.log("手机号码", phoneNum);
	
	//初始化sms_client
	let smsClient = new SMSClient({
		accessKeyId: 'LTAI5tD3zeMEbNZEM6CN5hXi',  //accessKeyId 前面提到要准备的
		secretAccessKey: 'ljLYenzGDQT9i3MYWgRyx4MXGOmXIp'  //secretAccessKey 前面提到要准备的
	});
	
	//6位随机数
	let str = getCode();
 
	// 开始发送短信
	smsClient.sendSMS({
		PhoneNumbers: phoneNum,
		SignName: "快速学习发送", //签名名称 前面提到要准备的
		TemplateCode: "SMS_476750549", //模版CODE  前面提到要准备的
		TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
	}).then(result => {
		console.log("result", result)
		let {Code} = result;
		if (Code == 'OK') {
			
			res.json({
				code: 0, 
				msg: 'success',
				sms: str
			})
			console.log(result)
		}
	}).catch(err => {
		console.log(err);
		res.json({
			code: 1, 
			msg: 'fail: ' + err.data.Message
		})
	})
 
});

router.get('/login',async(req,res)=>{
	const {password,pword,username} = req.query
	if(password==pword){
		const accessToken = jwt.sign({ username, password }, secretKey, { expiresIn: 60 * 15 });
    const refreshToken = jwt.sign({ username, password }, secretKey, { expiresIn: '7d' });
		res.send({
			code:200,
			token:{accessToken,refreshToken}
		})
	}else{
		res.send({
			code:400
		})
	}
})
 
module.exports = router;
 